/*-------------------------------------------------------------------------
 *
 * pgstatfuncs.c
 *	  访问各种形式的统计数据的函数
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  src/backend/utils/adt/pgstatfuncs.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/htup_details.h"
#include "access/xlog.h"
#include "access/xlogprefetcher.h"
#include "catalog/catalog.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_type.h"
#include "common/ip.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/postmaster.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/inet.h"
#include "utils/timestamp.h"

#define UINT32_ACCESS_ONCE(var)		 ((uint32)(*((volatile uint32 *)&(var))))

#define HAS_PGSTAT_PERMISSIONS(role)	 (has_privs_of_role(GetUserId(), ROLE_PG_READ_ALL_STATS) || has_privs_of_role(GetUserId(), role))

Datum pg_stat_get_numscans(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->numscans);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_returned(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_returned);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_fetched);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_inserted(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_inserted);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_updated(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_updated);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_deleted(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_deleted);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_tuples_hot_updated(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->tuples_hot_updated);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_live_tuples(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->n_live_tuples);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_dead_tuples(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->n_dead_tuples);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_mod_since_analyze(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->changes_since_analyze);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_ins_since_vacuum(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->inserts_since_vacuum);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_blocks_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->blocks_fetched);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_blocks_hit(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->blocks_hit);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_last_vacuum_time(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_tabentry->vacuum_timestamp;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_last_autovacuum_time(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_tabentry->autovac_vacuum_timestamp;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_last_analyze_time(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_tabentry->analyze_timestamp;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_last_autoanalyze_time(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_tabentry->autovac_analyze_timestamp;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_vacuum_count(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->vacuum_count);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_autovacuum_count(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->autovac_vacuum_count);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_analyze_count(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->analyze_count);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_autoanalyze_count(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatTabEntry *fc_tabentry;

	if ((fc_tabentry = pgstat_fetch_stat_tabentry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->autovac_analyze_count);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_function_calls(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_StatFuncEntry *fc_funcentry;

	if ((fc_funcentry = pgstat_fetch_stat_funcentry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	PG_RETURN_INT64(fc_funcentry->f_numcalls);
}

Datum pg_stat_get_function_total_time(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_StatFuncEntry *fc_funcentry;

	if ((fc_funcentry = pgstat_fetch_stat_funcentry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	/* 将计数器从微秒转为毫秒以供显示 */
	PG_RETURN_FLOAT8(((double) fc_funcentry->f_total_time) / 1000.0);
}

Datum pg_stat_get_function_self_time(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_StatFuncEntry *fc_funcentry;

	if ((fc_funcentry = pgstat_fetch_stat_funcentry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	/* 将计数器从微秒转为毫秒以供显示 */
	PG_RETURN_FLOAT8(((double) fc_funcentry->f_self_time) / 1000.0);
}

Datum pg_stat_get_backend_idset(PG_FUNCTION_ARGS)
{
	FuncCallContext *fc_funcctx;
	int		   *fc_fctx;
	int32		fc_result;

	/* 仅在函数的第一次调用时完成的工作 */
	if (SRF_IS_FIRSTCALL())
	{
		/* 为跨调用持久性创建一个函数上下文 */
		fc_funcctx = SRF_FIRSTCALL_INIT();

		fc_fctx = MemoryContextAlloc(fc_funcctx->multi_call_memory_ctx,
								  2 * sizeof(int));
		fc_funcctx->user_fctx = fc_fctx;

		fc_fctx[0] = 0;
		fc_fctx[1] = pgstat_fetch_stat_numbackends();
	}

	/* 每次调用函数时完成的工作 */
	fc_funcctx = SRF_PERCALL_SETUP();
	fc_fctx = fc_funcctx->user_fctx;

	fc_fctx[0] += 1;
	fc_result = fc_fctx[0];

	if (fc_result <= fc_fctx[1])
	{
		/* 当还有更多内容要发送时执行 */
		SRF_RETURN_NEXT(fc_funcctx, Int32GetDatum(fc_result));
	}
	else
	{
		/* 当没有更多内容时执行 */
		SRF_RETURN_DONE(fc_funcctx);
	}
}

/*
 * 返回命名命令的命令进度信息。
 */
Datum pg_stat_get_progress_info(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_PROGRESS_COLS	PGSTAT_NUM_PROGRESS_PARAM + 3
	int			fc_num_backends = pgstat_fetch_stat_numbackends();
	int			fc_curr_backend;
	char	   *fc_cmd = text_to_cstring(PG_GETARG_TEXT_PP(0));
	ProgressCommandType fc_cmdtype;
	ReturnSetInfo *fc_rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;

	/* 将命令名称转换为命令类型代码。 */
	if (pg_strcasecmp(fc_cmd, "VACUUM") == 0)
		fc_cmdtype = PROGRESS_COMMAND_VACUUM;
	else if (pg_strcasecmp(fc_cmd, "ANALYZE") == 0)
		fc_cmdtype = PROGRESS_COMMAND_ANALYZE;
	else if (pg_strcasecmp(fc_cmd, "CLUSTER") == 0)
		fc_cmdtype = PROGRESS_COMMAND_CLUSTER;
	else if (pg_strcasecmp(fc_cmd, "CREATE INDEX") == 0)
		fc_cmdtype = PROGRESS_COMMAND_CREATE_INDEX;
	else if (pg_strcasecmp(fc_cmd, "BASEBACKUP") == 0)
		fc_cmdtype = PROGRESS_COMMAND_BASEBACKUP;
	else if (pg_strcasecmp(fc_cmd, "COPY") == 0)
		fc_cmdtype = PROGRESS_COMMAND_COPY;
	else
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid command name: \"%s\"", fc_cmd)));

	InitMaterializedSRF(fcinfo, 0);

	/* 1 基于索引 */
	for (fc_curr_backend = 1; fc_curr_backend <= fc_num_backends; fc_curr_backend++)
	{
		LocalPgBackendStatus *fc_local_beentry;
		PgBackendStatus *fc_beentry;
		Datum		fc_values[PG_STAT_GET_PROGRESS_COLS];
		bool		fc_nulls[PG_STAT_GET_PROGRESS_COLS];
		int			fc_i;

		MemSet(fc_values, 0, sizeof(fc_values));
		MemSet(fc_nulls, 0, sizeof(fc_nulls));

		fc_local_beentry = pgstat_fetch_stat_local_beentry(fc_curr_backend);

		if (!fc_local_beentry)
			continue;

		fc_beentry = &fc_local_beentry->backendStatus;

		/*
		 * 仅报告正在运行给定命令的那些后端的值。
		 */
		if (!fc_beentry || fc_beentry->st_progress_command != fc_cmdtype)
			continue;

		/* 可供所有调用者访问的值 */
		fc_values[0] = Int32GetDatum(fc_beentry->st_procpid);
		fc_values[1] = ObjectIdGetDatum(fc_beentry->st_databaseid);

		/* 仅向角色成员显示其余的值，包括 relid */
		if (HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		{
			fc_values[2] = ObjectIdGetDatum(fc_beentry->st_progress_command_target);
			for (fc_i = 0; fc_i < PGSTAT_NUM_PROGRESS_PARAM; fc_i++)
				fc_values[fc_i + 3] = Int64GetDatum(fc_beentry->st_progress_param[fc_i]);
		}
		else
		{
			fc_nulls[2] = true;
			for (fc_i = 0; fc_i < PGSTAT_NUM_PROGRESS_PARAM; fc_i++)
				fc_nulls[fc_i + 3] = true;
		}

		tuplestore_putvalues(fc_rsinfo->setResult, fc_rsinfo->setDesc, fc_values, fc_nulls);
	}

	return (Datum) 0;
}

/*
 * 返回 PG 后端的活动。
 */
Datum pg_stat_get_activity(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_ACTIVITY_COLS	30
	int			fc_num_backends = pgstat_fetch_stat_numbackends();
	int			fc_curr_backend;
	int			fc_pid = PG_ARGISNULL(0) ? -1 : PG_GETARG_INT32(0);
	ReturnSetInfo *fc_rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;

	InitMaterializedSRF(fcinfo, 0);

	/* 1 基于索引 */
	for (fc_curr_backend = 1; fc_curr_backend <= fc_num_backends; fc_curr_backend++)
	{
		/* 对于每一行 */
		Datum		fc_values[PG_STAT_GET_ACTIVITY_COLS];
		bool		fc_nulls[PG_STAT_GET_ACTIVITY_COLS];
		LocalPgBackendStatus *fc_local_beentry;
		PgBackendStatus *fc_beentry;
		PGPROC	   *fc_proc;
		const char *fc_wait_event_type = NULL;
		const char *fc_wait_event = NULL;

		MemSet(fc_values, 0, sizeof(fc_values));
		MemSet(fc_nulls, 0, sizeof(fc_nulls));

		/* 获取列表中的下一个 */
		fc_local_beentry = pgstat_fetch_stat_local_beentry(fc_curr_backend);
		if (!fc_local_beentry)
		{
			int			fc_i;

			/* 如果查找特定的 PID，则忽略缺失的条目 */
			if (fc_pid != -1)
				continue;

			for (fc_i = 0; fc_i < lengthof(fc_nulls); fc_i++)
				fc_nulls[fc_i] = true;

			fc_nulls[5] = false;
			fc_values[5] = CStringGetTextDatum("<backend information not available>");

			tuplestore_putvalues(fc_rsinfo->setResult, fc_rsinfo->setDesc, fc_values, fc_nulls);
			continue;
		}

		fc_beentry = &fc_local_beentry->backendStatus;

		/* 如果查找特定的 PID，则忽略其他所有条目 */
		if (fc_pid != -1 && fc_beentry->st_procpid != fc_pid)
			continue;

		/* 可供所有调用者访问的值 */
		if (fc_beentry->st_databaseid != InvalidOid)
			fc_values[0] = ObjectIdGetDatum(fc_beentry->st_databaseid);
		else
			fc_nulls[0] = true;

		fc_values[1] = Int32GetDatum(fc_beentry->st_procpid);

		if (fc_beentry->st_userid != InvalidOid)
			fc_values[2] = ObjectIdGetDatum(fc_beentry->st_userid);
		else
			fc_nulls[2] = true;

		if (fc_beentry->st_appname)
			fc_values[3] = CStringGetTextDatum(fc_beentry->st_appname);
		else
			fc_nulls[3] = true;

		if (TransactionIdIsValid(fc_local_beentry->backend_xid))
			fc_values[15] = TransactionIdGetDatum(fc_local_beentry->backend_xid);
		else
			fc_nulls[15] = true;

		if (TransactionIdIsValid(fc_local_beentry->backend_xmin))
			fc_values[16] = TransactionIdGetDatum(fc_local_beentry->backend_xmin);
		else
			fc_nulls[16] = true;

		/* 仅对角色成员或 pg_read_all_stats 可用的值 */
		if (HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		{
			SockAddr	fc_zero_clientaddr;
			char	   *fc_clipped_activity;

			switch (fc_beentry->st_state)
			{
				case STATE_IDLE:
					fc_values[4] = CStringGetTextDatum("idle");
					break;
				case STATE_RUNNING:
					fc_values[4] = CStringGetTextDatum("active");
					break;
				case STATE_IDLEINTRANSACTION:
					fc_values[4] = CStringGetTextDatum("idle in transaction");
					break;
				case STATE_FASTPATH:
					fc_values[4] = CStringGetTextDatum("fastpath function call");
					break;
				case STATE_IDLEINTRANSACTION_ABORTED:
					fc_values[4] = CStringGetTextDatum("idle in transaction (aborted)");
					break;
				case STATE_DISABLED:
					fc_values[4] = CStringGetTextDatum("disabled");
					break;
				case STATE_UNDEFINED:
					fc_nulls[4] = true;
					break;
			}

			fc_clipped_activity = pgstat_clip_activity(fc_beentry->st_activity_raw);
#ifdef FDD
			if(NULL != fc_clipped_activity)
			{//将password后面跟的明文转换为一个‘*’，用于隐藏，即将 alter user u1 password 'Abcde-1234';select * from t1;
			 //变为  alter user u1 password *;select * from t1;
				int   fc_i = 0, fc_j=0;
				char *fc_passwordToken = NULL;

				for(fc_i=0; fc_clipped_activity[fc_i] != 0; fc_i++)
				{// todo 注意此处有bug，会将第二个引号后的内容都变为小写
					fc_clipped_activity[fc_i] = (char)pg_tolower((unsigned char)fc_clipped_activity[fc_i]);
				}
				fc_passwordToken = strstr(fc_clipped_activity, TOKEN_PASSWORD);
				if(NULL != fc_passwordToken)
				{
					fc_i = (fc_passwordToken - fc_clipped_activity) + strlen(TOKEN_PASSWORD);
					for(; fc_clipped_activity[fc_i] != 0 && fc_clipped_activity[fc_i] != '\''; fc_i++){}
					if(fc_clipped_activity[fc_i] != 0)
					{
						fc_clipped_activity[fc_i++] = '*';
						for(fc_j=fc_i; fc_clipped_activity[fc_j] != 0 && fc_clipped_activity[fc_j] != '\''; fc_j++){}
						if(fc_clipped_activity[fc_j] != 0)
						{
							for(fc_j++; fc_clipped_activity[fc_j] != 0; fc_j++)
							{
								fc_clipped_activity[fc_i] = fc_clipped_activity[fc_j];
								fc_i++;
							}
							fc_clipped_activity[fc_i] = 0;
						}
						
					}
				}
			}
#endif
			fc_values[5] = CStringGetTextDatum(fc_clipped_activity);
			pfree(fc_clipped_activity);

			/* leader_pid */
			fc_nulls[28] = true;

			fc_proc = BackendPidGetProc(fc_beentry->st_procpid);

			if (fc_proc == NULL && (fc_beentry->st_backendType != B_BACKEND))
			{
				/*
				 * 对于辅助进程，从存储在共享内存中的
				 * AuxiliaryProcs 中检索进程信息。
				 */
				fc_proc = AuxiliaryPidGetProc(fc_beentry->st_procpid);
			}

			/*
			 * 如果检索到了 PGPROC 条目，显示等待事件和锁
			 * 组领导者信息（如果有）。为了避免额外的开销，
			 * 不持有额外的锁，因此无法保证多个行之间的一致性。
			 */
			if (fc_proc != NULL)
			{
				uint32		fc_raw_wait_event;
				PGPROC	   *fc_leader;

				fc_raw_wait_event = UINT32_ACCESS_ONCE(fc_proc->wait_event_info);
				fc_wait_event_type = pgstat_get_wait_event_type(fc_raw_wait_event);
				fc_wait_event = pgstat_get_wait_event(fc_raw_wait_event);

				fc_leader = fc_proc->lockGroupLeader;

				/*
				 * 仅显示活动并行工作者的领导者。这样
				 * 并行组的领导者字段将保持为 NULL。
				 */
				if (fc_leader && fc_leader->pid != fc_beentry->st_procpid)
				{
					fc_values[28] = Int32GetDatum(fc_leader->pid);
					fc_nulls[28] = false;
				}
			}

			if (fc_wait_event_type)
				fc_values[6] = CStringGetTextDatum(fc_wait_event_type);
			else
				fc_nulls[6] = true;

			if (fc_wait_event)
				fc_values[7] = CStringGetTextDatum(fc_wait_event);
			else
				fc_nulls[7] = true;

			/*
			 * 不向 walsenders 暴露事务时间；这会导致监控混淆，
			 * 特别是因为我们无法保持时间的最新性。
			 */
			if (fc_beentry->st_xact_start_timestamp != 0 &&
				fc_beentry->st_backendType != B_WAL_SENDER)
				fc_values[8] = TimestampTzGetDatum(fc_beentry->st_xact_start_timestamp);
			else
				fc_nulls[8] = true;

			if (fc_beentry->st_activity_start_timestamp != 0)
				fc_values[9] = TimestampTzGetDatum(fc_beentry->st_activity_start_timestamp);
			else
				fc_nulls[9] = true;

			if (fc_beentry->st_proc_start_timestamp != 0)
				fc_values[10] = TimestampTzGetDatum(fc_beentry->st_proc_start_timestamp);
			else
				fc_nulls[10] = true;

			if (fc_beentry->st_state_start_timestamp != 0)
				fc_values[11] = TimestampTzGetDatum(fc_beentry->st_state_start_timestamp);
			else
				fc_nulls[11] = true;

			/* 一个零的客户端地址意味着我们不知道 */
			memset(&fc_zero_clientaddr, 0, sizeof(fc_zero_clientaddr));
			if (memcmp(&(fc_beentry->st_clientaddr), &fc_zero_clientaddr,
					   sizeof(fc_zero_clientaddr)) == 0)
			{
				fc_nulls[12] = true;
				fc_nulls[13] = true;
				fc_nulls[14] = true;
			}
			else
			{
				if (fc_beentry->st_clientaddr.addr.ss_family == AF_INET
#ifdef HAVE_IPV6
					|| fc_beentry->st_clientaddr.addr.ss_family == AF_INET6
#endif
					)
				{
					char		fc_remote_host[NI_MAXHOST];
					char		fc_remote_port[NI_MAXSERV];
					int			fc_ret;

					fc_remote_host[0] = '\0';
					fc_remote_port[0] = '\0';
					fc_ret = pg_getnameinfo_all(&fc_beentry->st_clientaddr.addr,
											 fc_beentry->st_clientaddr.salen,
											 fc_remote_host, sizeof(fc_remote_host),
											 fc_remote_port, sizeof(fc_remote_port),
											 NI_NUMERICHOST | NI_NUMERICSERV);
					if (fc_ret == 0)
					{
						clean_ipv6_addr(fc_beentry->st_clientaddr.addr.ss_family, fc_remote_host);
						fc_values[12] = DirectFunctionCall1(inet_in,
														 CStringGetDatum(fc_remote_host));
						if (fc_beentry->st_clienthostname &&
							fc_beentry->st_clienthostname[0])
							fc_values[13] = CStringGetTextDatum(fc_beentry->st_clienthostname);
						else
							fc_nulls[13] = true;
						fc_values[14] = Int32GetDatum(atoi(fc_remote_port));
					}
					else
					{
						fc_nulls[12] = true;
						fc_nulls[13] = true;
						fc_nulls[14] = true;
					}
				}
				else if (fc_beentry->st_clientaddr.addr.ss_family == AF_UNIX)
				{
					/*
					 * Unix 套接字总是会为主机报告 NULL，为端口报告 -1，因此可以判断
					 * 我们无法查看权限的连接或存在错误的连接。
					 */
					fc_nulls[12] = true;
					fc_nulls[13] = true;
					fc_values[14] = Int32GetDatum(-1);
				}
				else
				{
					/* 未知地址类型，应该永远不会发生 */
					fc_nulls[12] = true;
					fc_nulls[13] = true;
					fc_nulls[14] = true;
				}
			}
			/* 添加后端类型 */
			if (fc_beentry->st_backendType == B_BG_WORKER)
			{
				const char *fc_bgw_type;

				fc_bgw_type = GetBackgroundWorkerTypeByPid(fc_beentry->st_procpid);
				if (fc_bgw_type)
					fc_values[17] = CStringGetTextDatum(fc_bgw_type);
				else
					fc_nulls[17] = true;
			}
			else
				fc_values[17] =
					CStringGetTextDatum(GetBackendTypeDesc(fc_beentry->st_backendType));

			/* SSL 信息 */
			if (fc_beentry->st_ssl)
			{
				fc_values[18] = BoolGetDatum(true);	/* ssl */
				fc_values[19] = CStringGetTextDatum(fc_beentry->st_sslstatus->ssl_version);
				fc_values[20] = CStringGetTextDatum(fc_beentry->st_sslstatus->ssl_cipher);
				fc_values[21] = Int32GetDatum(fc_beentry->st_sslstatus->ssl_bits);

				if (fc_beentry->st_sslstatus->ssl_client_dn[0])
					fc_values[22] = CStringGetTextDatum(fc_beentry->st_sslstatus->ssl_client_dn);
				else
					fc_nulls[22] = true;

				if (fc_beentry->st_sslstatus->ssl_client_serial[0])
					fc_values[23] = DirectFunctionCall3(numeric_in,
													 CStringGetDatum(fc_beentry->st_sslstatus->ssl_client_serial),
													 ObjectIdGetDatum(InvalidOid),
													 Int32GetDatum(-1));
				else
					fc_nulls[23] = true;

				if (fc_beentry->st_sslstatus->ssl_issuer_dn[0])
					fc_values[24] = CStringGetTextDatum(fc_beentry->st_sslstatus->ssl_issuer_dn);
				else
					fc_nulls[24] = true;
			}
			else
			{
				fc_values[18] = BoolGetDatum(false);	/* ssl */
				fc_nulls[19] = fc_nulls[20] = fc_nulls[21] = fc_nulls[22] = fc_nulls[23] = fc_nulls[24] = true;
			}

			/* GSSAPI 信息 */
			if (fc_beentry->st_gss)
			{
				fc_values[25] = BoolGetDatum(fc_beentry->st_gssstatus->gss_auth); /* gss_auth */
				fc_values[26] = CStringGetTextDatum(fc_beentry->st_gssstatus->gss_princ);
				fc_values[27] = BoolGetDatum(fc_beentry->st_gssstatus->gss_enc);	/* 正在使用 GSS 加密 */
			}
			else
			{
				fc_values[25] = BoolGetDatum(false);	/* gss_auth */
				fc_nulls[26] = true;	/* 无 GSS 主体 */
				fc_values[27] = BoolGetDatum(false);	/* 未使用 GSS 加密 */
			}
			if (fc_beentry->st_query_id == 0)
				fc_nulls[29] = true;
			else
				fc_values[29] = UInt64GetDatum(fc_beentry->st_query_id);
		}
		else
		{
			/* 无权限查看此会话的数据 */
			fc_values[5] = CStringGetTextDatum("<insufficient privilege>");
			fc_nulls[4] = true;
			fc_nulls[6] = true;
			fc_nulls[7] = true;
			fc_nulls[8] = true;
			fc_nulls[9] = true;
			fc_nulls[10] = true;
			fc_nulls[11] = true;
			fc_nulls[12] = true;
			fc_nulls[13] = true;
			fc_nulls[14] = true;
			fc_nulls[17] = true;
			fc_nulls[18] = true;
			fc_nulls[19] = true;
			fc_nulls[20] = true;
			fc_nulls[21] = true;
			fc_nulls[22] = true;
			fc_nulls[23] = true;
			fc_nulls[24] = true;
			fc_nulls[25] = true;
			fc_nulls[26] = true;
			fc_nulls[27] = true;
			fc_nulls[28] = true;
			fc_nulls[29] = true;
		}

		tuplestore_putvalues(fc_rsinfo->setResult, fc_rsinfo->setDesc, fc_values, fc_nulls);

		/* 如果只请求了单个后端，并且我们找到了它，则退出。 */
		if (fc_pid != -1)
			break;
	}

	return (Datum) 0;
}


Datum pg_backend_pid(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT32(MyProcPid);
}


Datum pg_stat_get_backend_pid(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	PG_RETURN_INT32(fc_beentry->st_procpid);
}


Datum pg_stat_get_backend_dbid(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	PG_RETURN_OID(fc_beentry->st_databaseid);
}


Datum pg_stat_get_backend_userid(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	PG_RETURN_OID(fc_beentry->st_userid);
}


Datum pg_stat_get_backend_activity(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;
	const char *fc_activity;
	char	   *fc_clipped_activity;
	text	   *fc_ret;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		fc_activity = "<backend information not available>";
	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		fc_activity = "<insufficient privilege>";
	else if (*(fc_beentry->st_activity_raw) == '\0')
		fc_activity = "<command string not enabled>";
	else
		fc_activity = fc_beentry->st_activity_raw;

	fc_clipped_activity = pgstat_clip_activity(fc_activity);
	fc_ret = cstring_to_text(fc_activity);
	pfree(fc_clipped_activity);

	PG_RETURN_TEXT_P(fc_ret);
}

Datum pg_stat_get_backend_wait_event_type(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;
	PGPROC	   *fc_proc;
	const char *fc_wait_event_type = NULL;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		fc_wait_event_type = "<backend information not available>";
	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		fc_wait_event_type = "<insufficient privilege>";
	else if ((fc_proc = BackendPidGetProc(fc_beentry->st_procpid)) != NULL)
		fc_wait_event_type = pgstat_get_wait_event_type(fc_proc->wait_event_info);

	if (!fc_wait_event_type)
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(cstring_to_text(fc_wait_event_type));
}

Datum pg_stat_get_backend_wait_event(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;
	PGPROC	   *fc_proc;
	const char *fc_wait_event = NULL;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		fc_wait_event = "<backend information not available>";
	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		fc_wait_event = "<insufficient privilege>";
	else if ((fc_proc = BackendPidGetProc(fc_beentry->st_procpid)) != NULL)
		fc_wait_event = pgstat_get_wait_event(fc_proc->wait_event_info);

	if (!fc_wait_event)
		PG_RETURN_NULL();

	PG_RETURN_TEXT_P(cstring_to_text(fc_wait_event));
}


Datum pg_stat_get_backend_activity_start(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	TimestampTz fc_result;
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		PG_RETURN_NULL();

	fc_result = fc_beentry->st_activity_start_timestamp;

	/*
	 * 当前查询的开始时间未记录 -- 如果用户未启用查询级别的统计收集，
	 * 则会出现这种情况。
	 */
	if (fc_result == 0)
		PG_RETURN_NULL();

	PG_RETURN_TIMESTAMPTZ(fc_result);
}


Datum pg_stat_get_backend_xact_start(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	TimestampTz fc_result;
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		PG_RETURN_NULL();

	fc_result = fc_beentry->st_xact_start_timestamp;

	if (fc_result == 0)			/* 不在事务中 */
		PG_RETURN_NULL();

	PG_RETURN_TIMESTAMPTZ(fc_result);
}


Datum pg_stat_get_backend_start(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	TimestampTz fc_result;
	PgBackendStatus *fc_beentry;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		PG_RETURN_NULL();

	fc_result = fc_beentry->st_proc_start_timestamp;

	if (fc_result == 0)			/* 可能无法发生？ */
		PG_RETURN_NULL();

	PG_RETURN_TIMESTAMPTZ(fc_result);
}


Datum pg_stat_get_backend_client_addr(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;
	SockAddr	fc_zero_clientaddr;
	char		fc_remote_host[NI_MAXHOST];
	int			fc_ret;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		PG_RETURN_NULL();

	/* 一个零的客户端地址意味着我们不知道 */
	memset(&fc_zero_clientaddr, 0, sizeof(fc_zero_clientaddr));
	if (memcmp(&(fc_beentry->st_clientaddr), &fc_zero_clientaddr,
			   sizeof(fc_zero_clientaddr)) == 0)
		PG_RETURN_NULL();

	switch (fc_beentry->st_clientaddr.addr.ss_family)
	{
		case AF_INET:
#ifdef HAVE_IPV6
		case AF_INET6:
#endif
			break;
		default:
			PG_RETURN_NULL();
	}

	fc_remote_host[0] = '\0';
	fc_ret = pg_getnameinfo_all(&fc_beentry->st_clientaddr.addr,
							 fc_beentry->st_clientaddr.salen,
							 fc_remote_host, sizeof(fc_remote_host),
							 NULL, 0,
							 NI_NUMERICHOST | NI_NUMERICSERV);
	if (fc_ret != 0)
		PG_RETURN_NULL();

	clean_ipv6_addr(fc_beentry->st_clientaddr.addr.ss_family, fc_remote_host);

	PG_RETURN_INET_P(DirectFunctionCall1(inet_in,
										 CStringGetDatum(fc_remote_host)));
}

Datum pg_stat_get_backend_client_port(PG_FUNCTION_ARGS)
{
	int32		fc_beid = PG_GETARG_INT32(0);
	PgBackendStatus *fc_beentry;
	SockAddr	fc_zero_clientaddr;
	char		fc_remote_port[NI_MAXSERV];
	int			fc_ret;

	if ((fc_beentry = pgstat_fetch_stat_beentry(fc_beid)) == NULL)
		PG_RETURN_NULL();

	else if (!HAS_PGSTAT_PERMISSIONS(fc_beentry->st_userid))
		PG_RETURN_NULL();

	/* 一个零的客户端地址意味着我们不知道 */
	memset(&fc_zero_clientaddr, 0, sizeof(fc_zero_clientaddr));
	if (memcmp(&(fc_beentry->st_clientaddr), &fc_zero_clientaddr,
			   sizeof(fc_zero_clientaddr)) == 0)
		PG_RETURN_NULL();

	switch (fc_beentry->st_clientaddr.addr.ss_family)
	{
		case AF_INET:
#ifdef HAVE_IPV6
		case AF_INET6:
#endif
			break;
		case AF_UNIX:
			PG_RETURN_INT32(-1);
		default:
			PG_RETURN_NULL();
	}

	fc_remote_port[0] = '\0';
	fc_ret = pg_getnameinfo_all(&fc_beentry->st_clientaddr.addr,
							 fc_beentry->st_clientaddr.salen,
							 NULL, 0,
							 fc_remote_port, sizeof(fc_remote_port),
							 NI_NUMERICHOST | NI_NUMERICSERV);
	if (fc_ret != 0)
		PG_RETURN_NULL();

	PG_RETURN_DATUM(DirectFunctionCall1(int4in,
										CStringGetDatum(fc_remote_port)));
}


Datum pg_stat_get_db_numbackends(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int32		fc_result;
	int			fc_tot_backends = pgstat_fetch_stat_numbackends();
	int			fc_beid;

	fc_result = 0;
	for (fc_beid = 1; fc_beid <= fc_tot_backends; fc_beid++)
	{
		PgBackendStatus *fc_beentry = pgstat_fetch_stat_beentry(fc_beid);

		if (fc_beentry && fc_beentry->st_databaseid == fc_dbid)
			fc_result++;
	}

	PG_RETURN_INT32(fc_result);
}


Datum pg_stat_get_db_xact_commit(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_xact_commit);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_xact_rollback(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_xact_rollback);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_blocks_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_blocks_fetched);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_blocks_hit(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_blocks_hit);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_tuples_returned(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_tuples_returned);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_tuples_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_tuples_fetched);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_tuples_inserted(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_tuples_inserted);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_tuples_updated(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_tuples_updated);

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_tuples_deleted(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_tuples_deleted);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_stat_reset_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_dbentry->stat_reset_timestamp;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_db_temp_files(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_dbentry->n_temp_files;

	PG_RETURN_INT64(fc_result);
}


Datum pg_stat_get_db_temp_bytes(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_dbentry->n_temp_bytes;

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_tablespace(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_tablespace);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_lock(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_lock);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_snapshot(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_snapshot);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_bufferpin(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_bufferpin);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_startup_deadlock(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_startup_deadlock);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_conflict_all(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_conflict_tablespace +
						  fc_dbentry->n_conflict_lock +
						  fc_dbentry->n_conflict_snapshot +
						  fc_dbentry->n_conflict_bufferpin +
						  fc_dbentry->n_conflict_startup_deadlock);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_deadlocks(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_deadlocks);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_checksum_failures(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if (!DataChecksumsEnabled())
		PG_RETURN_NULL();

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_dbentry->n_checksum_failures);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_checksum_last_failure(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	TimestampTz fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	if (!DataChecksumsEnabled())
		PG_RETURN_NULL();

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = fc_dbentry->last_checksum_failure;

	if (fc_result == 0)
		PG_RETURN_NULL();
	else
		PG_RETURN_TIMESTAMPTZ(fc_result);
}

Datum pg_stat_get_db_blk_read_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	double		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	/* 将计数器从微秒转为毫秒以供显示 */
	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = ((double) fc_dbentry->n_block_read_time) / 1000.0;

	PG_RETURN_FLOAT8(fc_result);
}

Datum pg_stat_get_db_blk_write_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	double		fc_result;
	PgStat_StatDBEntry *fc_dbentry;

	/* 将计数器从微秒转为毫秒以供显示 */
	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) == NULL)
		fc_result = 0;
	else
		fc_result = ((double) fc_dbentry->n_block_write_time) / 1000.0;

	PG_RETURN_FLOAT8(fc_result);
}

Datum pg_stat_get_db_session_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	double		fc_result = 0.0;
	PgStat_StatDBEntry *fc_dbentry;

	/* 将计数器从微秒转为毫秒以供显示 */
	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = ((double) fc_dbentry->total_session_time) / 1000.0;

	PG_RETURN_FLOAT8(fc_result);
}

Datum pg_stat_get_db_active_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	double		fc_result = 0.0;
	PgStat_StatDBEntry *fc_dbentry;

	/* 将计数器从微秒转为毫秒以供显示 */
	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = ((double) fc_dbentry->total_active_time) / 1000.0;

	PG_RETURN_FLOAT8(fc_result);
}

Datum pg_stat_get_db_idle_in_transaction_time(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	double		fc_result = 0.0;
	PgStat_StatDBEntry *fc_dbentry;

	/* 将计数器从微秒转为毫秒以供显示 */
	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = ((double) fc_dbentry->total_idle_in_xact_time) / 1000.0;

	PG_RETURN_FLOAT8(fc_result);
}

Datum pg_stat_get_db_sessions(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result = 0;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = (int64) (fc_dbentry->n_sessions);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_sessions_abandoned(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result = 0;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = (int64) (fc_dbentry->n_sessions_abandoned);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_sessions_fatal(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result = 0;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = (int64) (fc_dbentry->n_sessions_fatal);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_db_sessions_killed(PG_FUNCTION_ARGS)
{
	Oid			fc_dbid = PG_GETARG_OID(0);
	int64		fc_result = 0;
	PgStat_StatDBEntry *fc_dbentry;

	if ((fc_dbentry = pgstat_fetch_stat_dbentry(fc_dbid)) != NULL)
		fc_result = (int64) (fc_dbentry->n_sessions_killed);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_bgwriter_timed_checkpoints(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_checkpointer()->timed_checkpoints);
}

Datum pg_stat_get_bgwriter_requested_checkpoints(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_checkpointer()->requested_checkpoints);
}

Datum pg_stat_get_bgwriter_buf_written_checkpoints(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_checkpointer()->buf_written_checkpoints);
}

Datum pg_stat_get_bgwriter_buf_written_clean(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_bgwriter()->buf_written_clean);
}

Datum pg_stat_get_bgwriter_maxwritten_clean(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_bgwriter()->maxwritten_clean);
}

Datum pg_stat_get_checkpoint_write_time(PG_FUNCTION_ARGS)
{
	/* 时间已经以毫秒为单位，只需转换为双精度以供展示 */
	PG_RETURN_FLOAT8((double)
					 pgstat_fetch_stat_checkpointer()->checkpoint_write_time);
}

Datum pg_stat_get_checkpoint_sync_time(PG_FUNCTION_ARGS)
{
	/* 时间已经以毫秒为单位，只需转换为双精度以供展示 */
	PG_RETURN_FLOAT8((double)
					 pgstat_fetch_stat_checkpointer()->checkpoint_sync_time);
}

Datum pg_stat_get_bgwriter_stat_reset_time(PG_FUNCTION_ARGS)
{
	PG_RETURN_TIMESTAMPTZ(pgstat_fetch_stat_bgwriter()->stat_reset_timestamp);
}

Datum pg_stat_get_buf_written_backend(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_checkpointer()->buf_written_backend);
}

Datum pg_stat_get_buf_fsync_backend(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_checkpointer()->buf_fsync_backend);
}

Datum pg_stat_get_buf_alloc(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT64(pgstat_fetch_stat_bgwriter()->buf_alloc);
}

/*
 * 返回 WAL 活动的统计信息
 */
Datum pg_stat_get_wal(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_WAL_COLS	9
	TupleDesc	fc_tupdesc;
	Datum		fc_values[PG_STAT_GET_WAL_COLS];
	bool		fc_nulls[PG_STAT_GET_WAL_COLS];
	char		fc_buf[256];
	PgStat_WalStats *fc_wal_stats;

	/* 初始化值和 NULL 标志数组 */
	MemSet(fc_values, 0, sizeof(fc_values));
	MemSet(fc_nulls, 0, sizeof(fc_nulls));

	/* 初始化元组描述中的属性信息 */
	fc_tupdesc = CreateTemplateTupleDesc(PG_STAT_GET_WAL_COLS);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "wal_records",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "wal_fpi",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "wal_bytes",
					   NUMERICOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "wal_buffers_full",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "wal_write",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 6, "wal_sync",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 7, "wal_write_time",
					   FLOAT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 8, "wal_sync_time",
					   FLOAT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 9, "stats_reset",
					   TIMESTAMPTZOID, -1, 0);

	BlessTupleDesc(fc_tupdesc);

	/* 获取 WAL 活动的统计信息 */
	fc_wal_stats = pgstat_fetch_stat_wal();

	/* 填充值和 NULL */
	fc_values[0] = Int64GetDatum(fc_wal_stats->wal_records);
	fc_values[1] = Int64GetDatum(fc_wal_stats->wal_fpi);

	/* 转换为数字。 */
	snprintf(fc_buf, sizeof fc_buf, UINT64_FORMAT, fc_wal_stats->wal_bytes);
	fc_values[2] = DirectFunctionCall3(numeric_in,
									CStringGetDatum(fc_buf),
									ObjectIdGetDatum(0),
									Int32GetDatum(-1));

	fc_values[3] = Int64GetDatum(fc_wal_stats->wal_buffers_full);
	fc_values[4] = Int64GetDatum(fc_wal_stats->wal_write);
	fc_values[5] = Int64GetDatum(fc_wal_stats->wal_sync);

	/* 将计数器从微秒转换为毫秒以供显示 */
	fc_values[6] = Float8GetDatum(((double) fc_wal_stats->wal_write_time) / 1000.0);
	fc_values[7] = Float8GetDatum(((double) fc_wal_stats->wal_sync_time) / 1000.0);

	fc_values[8] = TimestampTzGetDatum(fc_wal_stats->stat_reset_timestamp);

	/* 将记录作为 Datum 返回 */
	PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(fc_tupdesc, fc_values, fc_nulls)));
}

/*
 * 返回 SLRU 缓存的统计信息。
 */
Datum pg_stat_get_slru(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_SLRU_COLS	9
	ReturnSetInfo *fc_rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	int			fc_i;
	PgStat_SLRUStats *fc_stats;

	InitMaterializedSRF(fcinfo, 0);

	/* 从累积统计系统请求 SLRU 统计信息 */
	fc_stats = pgstat_fetch_slru();

	for (fc_i = 0;; fc_i++)
	{
		/* 对于每一行 */
		Datum		fc_values[PG_STAT_GET_SLRU_COLS];
		bool		fc_nulls[PG_STAT_GET_SLRU_COLS];
		PgStat_SLRUStats fc_stat;
		const char *fc_name;

		fc_name = pgstat_get_slru_name(fc_i);

		if (!fc_name)
			break;

		fc_stat = fc_stats[fc_i];
		MemSet(fc_values, 0, sizeof(fc_values));
		MemSet(fc_nulls, 0, sizeof(fc_nulls));

		fc_values[0] = PointerGetDatum(cstring_to_text(fc_name));
		fc_values[1] = Int64GetDatum(fc_stat.blocks_zeroed);
		fc_values[2] = Int64GetDatum(fc_stat.blocks_hit);
		fc_values[3] = Int64GetDatum(fc_stat.blocks_read);
		fc_values[4] = Int64GetDatum(fc_stat.blocks_written);
		fc_values[5] = Int64GetDatum(fc_stat.blocks_exists);
		fc_values[6] = Int64GetDatum(fc_stat.flush);
		fc_values[7] = Int64GetDatum(fc_stat.truncate);
		fc_values[8] = TimestampTzGetDatum(fc_stat.stat_reset_timestamp);

		tuplestore_putvalues(fc_rsinfo->setResult, fc_rsinfo->setDesc, fc_values, fc_nulls);
	}

	return (Datum) 0;
}

Datum pg_stat_get_xact_numscans(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_numscans);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_returned(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_tuples_returned);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_tuples_fetched);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_inserted(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;
	PgStat_TableXactStatus *fc_trans;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
	{
		fc_result = fc_tabentry->t_counts.t_tuples_inserted;
		/* 活跃的子事务计数尚未在 t_tuples_inserted 中 */
		for (fc_trans = fc_tabentry->trans; fc_trans != NULL; fc_trans = fc_trans->upper)
			fc_result += fc_trans->tuples_inserted;
	}

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_updated(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;
	PgStat_TableXactStatus *fc_trans;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
	{
		fc_result = fc_tabentry->t_counts.t_tuples_updated;
		/* 活跃的子事务计数尚未在 t_tuples_updated 中 */
		for (fc_trans = fc_tabentry->trans; fc_trans != NULL; fc_trans = fc_trans->upper)
			fc_result += fc_trans->tuples_updated;
	}

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_deleted(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;
	PgStat_TableXactStatus *fc_trans;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
	{
		fc_result = fc_tabentry->t_counts.t_tuples_deleted;
		/* 活跃的子事务计数尚未在 t_tuples_deleted 中 */
		for (fc_trans = fc_tabentry->trans; fc_trans != NULL; fc_trans = fc_trans->upper)
			fc_result += fc_trans->tuples_deleted;
	}

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_tuples_hot_updated(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_tuples_hot_updated);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_blocks_fetched(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_blocks_fetched);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_blocks_hit(PG_FUNCTION_ARGS)
{
	Oid			fc_relid = PG_GETARG_OID(0);
	int64		fc_result;
	PgStat_TableStatus *fc_tabentry;

	if ((fc_tabentry = find_tabstat_entry(fc_relid)) == NULL)
		fc_result = 0;
	else
		fc_result = (int64) (fc_tabentry->t_counts.t_blocks_hit);

	PG_RETURN_INT64(fc_result);
}

Datum pg_stat_get_xact_function_calls(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_BackendFunctionEntry *fc_funcentry;

	if ((fc_funcentry = find_funcstat_entry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	PG_RETURN_INT64(fc_funcentry->f_counts.f_numcalls);
}

Datum pg_stat_get_xact_function_total_time(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_BackendFunctionEntry *fc_funcentry;

	if ((fc_funcentry = find_funcstat_entry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	PG_RETURN_FLOAT8(INSTR_TIME_GET_MILLISEC(fc_funcentry->f_counts.f_total_time));
}

Datum pg_stat_get_xact_function_self_time(PG_FUNCTION_ARGS)
{
	Oid			fc_funcid = PG_GETARG_OID(0);
	PgStat_BackendFunctionEntry *fc_funcentry;

	if ((fc_funcentry = find_funcstat_entry(fc_funcid)) == NULL)
		PG_RETURN_NULL();
	PG_RETURN_FLOAT8(INSTR_TIME_GET_MILLISEC(fc_funcentry->f_counts.f_self_time));
}


/* 获取当前统计快照的时间戳 */
Datum pg_stat_get_snapshot_timestamp(PG_FUNCTION_ARGS)
{
	bool		fc_have_snapshot;
	TimestampTz fc_ts;

	fc_ts = pgstat_get_stat_snapshot_timestamp(&fc_have_snapshot);

	if (!fc_have_snapshot)
		PG_RETURN_NULL();

	PG_RETURN_TIMESTAMPTZ(fc_ts);
}

/* 丢弃活动的统计快照 */
Datum pg_stat_clear_snapshot(PG_FUNCTION_ARGS)
{
	pgstat_clear_snapshot();

	PG_RETURN_VOID();
}


/* 强制在下一个时机报告统计信息 */
Datum pg_stat_force_next_flush(PG_FUNCTION_ARGS)
{
	pgstat_force_next_flush();

	PG_RETURN_VOID();
}


/* 重置当前数据库的所有计数器 */
Datum pg_stat_reset(PG_FUNCTION_ARGS)
{
	pgstat_reset_counters();

	PG_RETURN_VOID();
}

/* 重置某些共享集群范围的计数器 */
Datum pg_stat_reset_shared(PG_FUNCTION_ARGS)
{
	char	   *fc_target = text_to_cstring(PG_GETARG_TEXT_PP(0));

	if (strcmp(fc_target, "archiver") == 0)
		pgstat_reset_of_kind(PGSTAT_KIND_ARCHIVER);
	else if (strcmp(fc_target, "bgwriter") == 0)
	{
		/*
		 * 历史上，检查点是 bgwriter 的一部分，暂时继续重置
		 * 两者。
		 */
		pgstat_reset_of_kind(PGSTAT_KIND_BGWRITER);
		pgstat_reset_of_kind(PGSTAT_KIND_CHECKPOINTER);
	}
	else if (strcmp(fc_target, "recovery_prefetch") == 0)
		XLogPrefetchResetStats();
	else if (strcmp(fc_target, "wal") == 0)
		pgstat_reset_of_kind(PGSTAT_KIND_WAL);
	else
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("unrecognized reset target: \"%s\"", fc_target),
				 errhint("Target must be \"archiver\", \"bgwriter\", \"recovery_prefetch\", or \"wal\".")));

	PG_RETURN_VOID();
}

/*
 * 重置单个对象的统计信息，该对象可能属于当前
 * 数据库或在集群中所有数据库之间共享。
 */
Datum pg_stat_reset_single_table_counters(PG_FUNCTION_ARGS)
{
	Oid			fc_taboid = PG_GETARG_OID(0);
	Oid			fc_dboid = (IsSharedRelation(fc_taboid) ? InvalidOid : MyDatabaseId);

	pgstat_reset(PGSTAT_KIND_RELATION, fc_dboid, fc_taboid);

	PG_RETURN_VOID();
}

Datum pg_stat_reset_single_function_counters(PG_FUNCTION_ARGS)
{
	Oid			fc_funcoid = PG_GETARG_OID(0);

	pgstat_reset(PGSTAT_KIND_FUNCTION, MyDatabaseId, fc_funcoid);

	PG_RETURN_VOID();
}

/* 重置 SLRU 计数器（特定的或所有的）。 */
Datum pg_stat_reset_slru(PG_FUNCTION_ARGS)
{
	char	   *fc_target = NULL;

	if (PG_ARGISNULL(0))
		pgstat_reset_of_kind(PGSTAT_KIND_SLRU);
	else
	{
		fc_target = text_to_cstring(PG_GETARG_TEXT_PP(0));
		pgstat_reset_slru(fc_target);
	}

	PG_RETURN_VOID();
}

/* 重置复制槽统计信息（特定的或所有的）。 */
Datum pg_stat_reset_replication_slot(PG_FUNCTION_ARGS)
{
	char	   *fc_target = NULL;

	if (PG_ARGISNULL(0))
		pgstat_reset_of_kind(PGSTAT_KIND_REPLSLOT);
	else
	{
		fc_target = text_to_cstring(PG_GETARG_TEXT_PP(0));
		pgstat_reset_replslot(fc_target);
	}

	PG_RETURN_VOID();
}

/* 重置订阅统计信息（特定的或所有的） */
Datum pg_stat_reset_subscription_stats(PG_FUNCTION_ARGS)
{
	Oid			fc_subid;

	if (PG_ARGISNULL(0))
	{
		/* 清除所有订阅统计信息 */
		pgstat_reset_of_kind(PGSTAT_KIND_SUBSCRIPTION);
	}
	else
	{
		fc_subid = PG_GETARG_OID(0);

		if (!OidIsValid(fc_subid))
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("invalid subscription OID %u", fc_subid)));
		pgstat_reset(PGSTAT_KIND_SUBSCRIPTION, InvalidOid, fc_subid);
	}

	PG_RETURN_VOID();
}

Datum pg_stat_get_archiver(PG_FUNCTION_ARGS)
{
	TupleDesc	fc_tupdesc;
	Datum		fc_values[7];
	bool		fc_nulls[7];
	PgStat_ArchiverStats *fc_archiver_stats;

	/* 初始化值和 NULL 标志数组 */
	MemSet(fc_values, 0, sizeof(fc_values));
	MemSet(fc_nulls, 0, sizeof(fc_nulls));

	/* 初始化元组描述中的属性信息 */
	fc_tupdesc = CreateTemplateTupleDesc(7);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "archived_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "last_archived_wal",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "last_archived_time",
					   TIMESTAMPTZOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "failed_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "last_failed_wal",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 6, "last_failed_time",
					   TIMESTAMPTZOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 7, "stats_reset",
					   TIMESTAMPTZOID, -1, 0);

	BlessTupleDesc(fc_tupdesc);

	/* 获取归档进程的统计信息 */
	fc_archiver_stats = pgstat_fetch_stat_archiver();

	/* 填充值和 NULL */
	fc_values[0] = Int64GetDatum(fc_archiver_stats->archived_count);
	if (*(fc_archiver_stats->last_archived_wal) == '\0')
		fc_nulls[1] = true;
	else
		fc_values[1] = CStringGetTextDatum(fc_archiver_stats->last_archived_wal);

	if (fc_archiver_stats->last_archived_timestamp == 0)
		fc_nulls[2] = true;
	else
		fc_values[2] = TimestampTzGetDatum(fc_archiver_stats->last_archived_timestamp);

	fc_values[3] = Int64GetDatum(fc_archiver_stats->failed_count);
	if (*(fc_archiver_stats->last_failed_wal) == '\0')
		fc_nulls[4] = true;
	else
		fc_values[4] = CStringGetTextDatum(fc_archiver_stats->last_failed_wal);

	if (fc_archiver_stats->last_failed_timestamp == 0)
		fc_nulls[5] = true;
	else
		fc_values[5] = TimestampTzGetDatum(fc_archiver_stats->last_failed_timestamp);

	if (fc_archiver_stats->stat_reset_timestamp == 0)
		fc_nulls[6] = true;
	else
		fc_values[6] = TimestampTzGetDatum(fc_archiver_stats->stat_reset_timestamp);

	/* 将记录作为 Datum 返回 */
	PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(fc_tupdesc, fc_values, fc_nulls)));
}

/*
 * 获取复制槽的统计信息。如果槽统计信息不可用，
 * 返回所有零的统计信息。
 */
Datum pg_stat_get_replication_slot(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_REPLICATION_SLOT_COLS 10
	text	   *fc_slotname_text = PG_GETARG_TEXT_P(0);
	NameData	fc_slotname;
	TupleDesc	fc_tupdesc;
	Datum		fc_values[PG_STAT_GET_REPLICATION_SLOT_COLS];
	bool		fc_nulls[PG_STAT_GET_REPLICATION_SLOT_COLS];
	PgStat_StatReplSlotEntry *fc_slotent;
	PgStat_StatReplSlotEntry fc_allzero;

	/* 初始化值和 NULL 标志数组 */
	MemSet(fc_values, 0, sizeof(fc_values));
	MemSet(fc_nulls, 0, sizeof(fc_nulls));

	/* 初始化元组描述中的属性信息 */
	fc_tupdesc = CreateTemplateTupleDesc(PG_STAT_GET_REPLICATION_SLOT_COLS);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "slot_name",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "spill_txns",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "spill_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "spill_bytes",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "stream_txns",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 6, "stream_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 7, "stream_bytes",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 8, "total_txns",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 9, "total_bytes",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 10, "stats_reset",
					   TIMESTAMPTZOID, -1, 0);
	BlessTupleDesc(fc_tupdesc);

	namestrcpy(&fc_slotname, text_to_cstring(fc_slotname_text));
	fc_slotent = pgstat_fetch_replslot(fc_slotname);
	if (!fc_slotent)
	{
		/*
		 * 如果找不到槽，则初始化其统计信息。这在
		 * 创建槽消息丢失的情况下是可能的。
		 */
		memset(&fc_allzero, 0, sizeof(PgStat_StatReplSlotEntry));
		fc_slotent = &fc_allzero;
	}

	fc_values[0] = CStringGetTextDatum(NameStr(fc_slotname));
	fc_values[1] = Int64GetDatum(fc_slotent->spill_txns);
	fc_values[2] = Int64GetDatum(fc_slotent->spill_count);
	fc_values[3] = Int64GetDatum(fc_slotent->spill_bytes);
	fc_values[4] = Int64GetDatum(fc_slotent->stream_txns);
	fc_values[5] = Int64GetDatum(fc_slotent->stream_count);
	fc_values[6] = Int64GetDatum(fc_slotent->stream_bytes);
	fc_values[7] = Int64GetDatum(fc_slotent->total_txns);
	fc_values[8] = Int64GetDatum(fc_slotent->total_bytes);

	if (fc_slotent->stat_reset_timestamp == 0)
		fc_nulls[9] = true;
	else
		fc_values[9] = TimestampTzGetDatum(fc_slotent->stat_reset_timestamp);

	/* 将记录作为 Datum 返回 */
	PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(fc_tupdesc, fc_values, fc_nulls)));
}

/*
 * 获取给定订阅的统计信息。如果
 * 订阅统计信息不可用，返回所有零的统计信息。
 */
Datum pg_stat_get_subscription_stats(PG_FUNCTION_ARGS)
{
#define PG_STAT_GET_SUBSCRIPTION_STATS_COLS	4
	Oid			fc_subid = PG_GETARG_OID(0);
	TupleDesc	fc_tupdesc;
	Datum		fc_values[PG_STAT_GET_SUBSCRIPTION_STATS_COLS];
	bool		fc_nulls[PG_STAT_GET_SUBSCRIPTION_STATS_COLS];
	PgStat_StatSubEntry *fc_subentry;
	PgStat_StatSubEntry fc_allzero;

	/* 获取订阅统计信息 */
	fc_subentry = pgstat_fetch_stat_subscription(fc_subid);

	/* 初始化元组描述中的属性信息 */
	fc_tupdesc = CreateTemplateTupleDesc(PG_STAT_GET_SUBSCRIPTION_STATS_COLS);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "subid",
					   OIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "apply_error_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "sync_error_count",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "stats_reset",
					   TIMESTAMPTZOID, -1, 0);
	BlessTupleDesc(fc_tupdesc);

	/* 初始化值和 NULL 标志数组 */
	MemSet(fc_values, 0, sizeof(fc_values));
	MemSet(fc_nulls, 0, sizeof(fc_nulls));

	if (!fc_subentry)
	{
		/* 如果未找到订阅，则初始化其统计信息 */
		memset(&fc_allzero, 0, sizeof(PgStat_StatSubEntry));
		fc_subentry = &fc_allzero;
	}

	/* subid */
	fc_values[0] = ObjectIdGetDatum(fc_subid);

	/* apply_error_count */
	fc_values[1] = Int64GetDatum(fc_subentry->apply_error_count);

	/* sync_error_count */
	fc_values[2] = Int64GetDatum(fc_subentry->sync_error_count);

	/* stats_reset */
	if (fc_subentry->stat_reset_timestamp == 0)
		fc_nulls[3] = true;
	else
		fc_values[3] = TimestampTzGetDatum(fc_subentry->stat_reset_timestamp);

	/* 将记录作为 Datum 返回 */
	PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(fc_tupdesc, fc_values, fc_nulls)));
}

/*
 * 检查提供的类型、数据库 oid 和对象 oid 的对象是否存在统计信息。
 *
 * 这对于测试很有用，但实际上没有其他用途。因此未
 * 被文档化。
 */
Datum pg_stat_have_stats(PG_FUNCTION_ARGS)
{
	char	   *fc_stats_type = text_to_cstring(PG_GETARG_TEXT_P(0));
	Oid			fc_dboid = PG_GETARG_OID(1);
	Oid			fc_objoid = PG_GETARG_OID(2);
	PgStat_Kind fc_kind = pgstat_get_kind_from_str(fc_stats_type);

	PG_RETURN_BOOL(pgstat_have_entry(fc_kind, fc_dboid, fc_objoid));
}
